<!--
 * @LastEditors: 杜康
 * @LastEditTime: 2021-09-15 19:19:14
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>functional 组件测试</title>
</head>

<body>
  <div id="app">
    <smart-item :data="data"></smart-item>
    <button @click="change('img')">切换图片组件</button>
    <button @click="change('video')">切换视频组件</button>
    <button @click="change('text')">切换文本组件</button>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        data: {}
      },
      methods: {
        change: function (type) {
          if (type === 'img') {
            this.data = {
              type: 'img',
              url: 'https://raw.githubusercontent.com/iview/iview/master/assets/logo.png'
            }
          } else if (type === 'video') {
            this.data = {
              type: 'video',
              url: 'https://vjs.zencdn.net/v/oceans.mp4'
            }
          } else {
            this.data = {
              type: 'text',
              content: '这是一段纯文本'
            }
          }
        }
      },
      created: function () {
        this.change('img');
      }
    })
    var ImgItem = {
      props: ['data'],
      render: function (createElement) {
        var _this = this
        return createElement('div', [
          createElement('p', '图片组件'),
          createElement('img', {
            attrs: {
              src: _this.data.url
            }
          })
        ])
      }
    }
    var VideoItem = {
      props: ['data'],
      render: function (createElement) {
        var _this = this
        return createElement('div', [
          createElement('p', '视频组件'),
          createElement('video', {
            attrs: {
              src: _this.data.url,
              controls: 'controls',
              autoplay: 'autoplay'
            }
          })
        ])
      }
    }
    var TextItem = {
      props: ['data'],
      render: function (createElement) {
        var _this = this
        return createElement('div', [
          createElement('p', '纯文本组件'),
          createElement('p', _this.data.text)
        ])
      }
    }
    Vue.component('smart-item', {
      functional: true,
      render: function (createElement, context) {
        function getComponent() {
          var data = context.props.data
          if (data.type === 'img') return ImgItem
          if (data.type === 'video') return VideoItem
          return TextItem
        }
        return createElement(
          getComponent(), {
            props: {
              data: context.props.data
            }
          },
          context.children
        )
      },
      props: {
        data: {
          type: Object,
          required: true
        }
      }
    })
  </script>
</body>

</html>